/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package business;

import entity.User;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

/**
 *
 * Class that manages the User Browsing functionality. It's a Session Bean
 * injected everytime the system needs to search users in the DataBase.
 *
 * @author dami
 */
@Stateless
public class SearchingManager implements Serializable {

    @PersistenceContext
    private EntityManager em;

    /**
     * Search for ssers that have the first name, the last one or the email
     * equal to the text inserted by the user. If the user search by first and
     * last name, the search will find the users with first name and last name
     * equal to the text.
     *
     * @param text the text inserted by the User
     * @return the list of users found in the database matching with the text
     */
    public List<User> search(String text) {
        Set<User> userFirstResults = new HashSet();
        String arrayRicerca[];

        TypedQuery<User> findPerString = em.createQuery("SELECT u FROM User u WHERE (u.firstName LIKE :fname OR u.lastName LIKE :lname OR u.email LIKE :email)", User.class);
        TypedQuery<User> findPerName = em.createQuery("SELECT u FROM User u WHERE (u.firstName LIKE :fname AND u.lastName LIKE :lname) OR (u.firstName LIKE :lname AND u.lastName LIKE :fname)", User.class);

        System.out.println("searchmanager.search() in corso");
        if (text.startsWith(" ") || text.endsWith(" ")) {
            return new ArrayList();
        } else {
            if (text.contains(" ")) {
                arrayRicerca = text.split(" ");
                if (arrayRicerca.length > 2) {
                    userFirstResults = new HashSet();
                } else {
                    findPerName.setParameter("fname", "%" + arrayRicerca[0] + "%");
                    findPerName.setParameter("lname", "%" + arrayRicerca[1] + "%");
                    userFirstResults.addAll(findPerName.getResultList());
                }
            } else {
                findPerString.setParameter("fname", "%" + text + "%");
                findPerString.setParameter("lname", "%" + text + "%");
                findPerString.setParameter("email", "%" + text + "%");

                userFirstResults.addAll(findPerString.getResultList());
            }
        }
        List<User> userResults = new ArrayList(userFirstResults);
        return userResults;

    }

}
